<template>
  <view class="background">
    <view class="repair-info">
      <view style="display: flex;flex-direction: row;align-items: center;">
        <view style="width:20%;">服务地址</view>  <u-input style="margin-left: 30rpx;" placeholder="请填写服务地址" v-model="reparForm.dormId" /></view>
      <view style="margin-top: 40rpx;margin-bottom: 40rpx;">现场照片</view>
      <image v-if="reparForm.image" :src="reparForm.image" mode="widthFix"></image>
      <view v-else class="upload-button" @click="chooseAndUploadImage">+</view>

      <view style="margin-top: 40rpx;margin-bottom: 40rpx;">详情描述</view>
      <textarea class="input" type="text" v-model="reparForm.description" placeholder="请详细描述需要维修项"/>
    </view>
    <view class="user-info">
      <view style="display: flex;flex-direction: row;align-items: center;">
        <view style="width:20%;">联系人</view>  <u-input style="margin-left: 30rpx;" placeholder="请填写联系人" v-model="contactName" />
      </view>
      <view style="display: flex;flex-direction: row;align-items: center;">
        <view style="width:20%;">联系方式</view>  <u-input style="margin-left: 30rpx;" placeholder="请填写联系方式" v-model="contact" />
      </view>
    </view>
      <u-button style="border-radius: 50px;height:80rpx;width:90%;margin-top: 80rpx;" type="primary" @click="repair()">立即提交</u-button>
  </view>

</template>

<script>
import request from '@/common/request.js'
import student from '@/api/student/index.js'
import store from '@/store'
export default {
  data () {
    return {
      reparForm: {
        dormId: '',
        description: '',
        image: '',
        repairType: ''
      },
      contact: '',
      contactName:'',
      imageUrl: ''
    }
  },
  methods: {
    async repair() {
      try {
        const res = await student.repairRequest(this.reparForm)
        if (res.code == 200) {
          uni.showModal({
            content: '报修申请成功',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            success: (res) => {
              uni.navigateTo({
                url: '/pages/repair/orderList',
              });
            },
            fail: () => {
              uni.navigateTo({
                url: '/pages/repair/orderList',
              });
            }
          });

        }
        else {
          uni.showToast({
            title: '报修申请失败',
            icon: 'none', // 可选值：'success', 'loading', 'none'
            duration: 2000, // 显示时长，单位为毫秒
            mask: true // 是否显示透明蒙层
          });
        }
        // 处理响应数据
        console.log('返回数据:', res)
      } catch (error) {
        // 处理错误
        console.error('错误:', error)
      }
    },
    async chooseAndUploadImage() {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '正在选择图片',
          mask: true
        });

        // 使用 uni.chooseImage 选择图片
        const chooseRes = await uni.chooseImage({
          count: 1, // 允许选择的图片数量
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'] // 可以指定来源是相册还是相机，默认二者都有
        });
        console.log('chooseRes',chooseRes)
        console.log('路径',chooseRes[1].tempFilePaths[0])
        // if (tempFilePaths.length === 0) {
        //   console.warn('没有选择任何文件');
        //   return;
        // }

        // 使用 uni.uploadFile 上传图片
        const uploadRes = await this.uploadFile(chooseRes[1].tempFilePaths[0]);

        // 设置图片 URL 到 data 中
        this.reparForm.image= uploadRes.data

        // 隐藏加载提示
        uni.hideLoading();
        uni.showToast({
          title: '图片上传成功',
          icon: 'success'
        });
      } catch (error) {
        console.error('处理上传图片时发生错误:', error);
        uni.hideLoading();
        uni.showToast({
          title: '处理上传图片时发生错误',
          icon: 'none'
        });
      }
    },
    async uploadFile(filePath) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '正在上传图片',
          mask: true
        });

        // 调用 uni.uploadFile 上传图片
        const res = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: 'http://localhost:8185/news/uploadImage', // 开发者服务器 url
            filePath: filePath, // 要上传文件资源的路径
            name: 'file', // 文件对应的 key
            success: (uploadRes) => {
              resolve(uploadRes);
            },
            fail: (err) => {
              reject(err);
            }
          });
        });

        // 解析 JSON 响应
        const responseData = JSON.parse(res.data);

        if (responseData.code == 200) {
          return responseData; // 返回解析后的响应数据
        } else {
          throw new Error(`上传失败: ${responseData}`);
        }
      } catch (error) {
        console.error('上传图片失败:', error);
        throw error;
      } finally {
        // 确保隐藏加载提示
        uni.hideLoading();
      }
    }
  
  },
  async onLoad(option) {
    this.reparForm.repairType = option.repairType
    console.log(this.reparForm.repairType)
    console.log(store.getters.getUserInfo)
    this.contact = store.getters.getUserInfo.contact
    this.contactName = store.getters.getUserInfo.name
  }
}

</script>



<style>
.input {
  display: block;
  height: 200rpx;
  background-color: #e4e7ed;
  border-radius: 20rpx;
  width: 95%;
  padding: 20rpx;
}
.background {
  display: flex;
  background-color: #f3f4f6;
  width: 100%;
  height: 100vh;
  flex-direction: column; /* 使子元素垂直排列 */
}
.repair-info {
  height: 45vh;
  border-radius: 40rpx;
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  width:90%;
}
.user-info {
  border-radius: 40rpx;
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  width:90%;
}
image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.upload-button {
  width: 180rpx;
  height: 180rpx;
  border-radius: 20rpx;
  background-color: #f4f4f5;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #909399;
}
</style>